//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package api_common

import (
	"context"
	"fmt"

	"atomgit.com/openlinksaas/api-server/dao"
	"atomgit.com/openlinksaas/api-server/dao/project_dao"
	"atomgit.com/openlinksaas/api-server/dao/project_entry_dao"
	"atomgit.com/openlinksaas/proto-gen-go.git/events/events_entry"
	"atomgit.com/openlinksaas/proto-gen-go.git/events_api"
	"github.com/google/uuid"
	"go.mongodb.org/mongo-driver/mongo"
	"google.golang.org/protobuf/types/known/anypb"
)

func AddRemoveEntryEvent(
	sessionItem *dao.SessionDbItem,
	projectItem *project_dao.ProjectInfoDbItem,
	entryItem *project_entry_dao.EntryInfoDbItem,
	nowTime int64) {
	eventData, err := anypb.New(&events_entry.RemoveEvent{
		EntryId:    entryItem.EntryId,
		EntryType:  entryItem.EntryType,
		EntryTitle: entryItem.EntryTitle,
	})
	if err != nil {
		fmt.Println(err)
		return
	}

	dbSess, err := dao.StartSession()
	if err != nil {
		fmt.Println(err)
		return
	}
	defer dao.EndSession(dbSess)
	dbSess.WithTransaction(context.Background(), func(sessCtx mongo.SessionContext) (interface{}, error) {
		err := AddEvent(sessCtx, &events_api.Event{
			EventId:         uuid.NewString(),
			UserId:          sessionItem.UserId,
			UserDisplayName: sessionItem.DisplayName,
			ProjectId:       projectItem.ProjectId,
			ProjectName:     projectItem.BasicInfo.ProjectName,
			EventType:       events_api.EVENT_TYPE_EVENT_TYPE_ENTRY,
			EventTime:       nowTime,
			RefType:         events_api.EVENT_REF_TYPE_EVENT_REF_TYPE_PROJECT,
			RefId:           projectItem.ProjectId,
			EventData:       eventData,
		}, false, "", "")
		if err != nil {
			fmt.Println(err)
		}
		return nil, err
	})
}

func CheckEntryCanUpdate(sessionItem *dao.SessionDbItem, projectItem *project_dao.ProjectInfoDbItem,
	roleItem *project_dao.RoleInfoDbItem, entryItem *project_entry_dao.EntryInfoDbItem) bool {
	if projectItem.Closed {
		return false
	}
	if projectItem.OwnerUserId == sessionItem.UserId || roleItem.BasicInfo.Admin || entryItem.CreateUserId == sessionItem.UserId {
		return true
	}
	if entryItem.EntryPerm.UpdateForAll {
		return true
	}
	for _, userId := range entryItem.EntryPerm.ExtraUpdateUserIdList {
		if userId == sessionItem.UserId {
			return true
		}
	}
	return false
}

func CheckEntryCanRemove(sessionItem *dao.SessionDbItem, projectItem *project_dao.ProjectInfoDbItem,
	roleItem *project_dao.RoleInfoDbItem, entryItem *project_entry_dao.EntryInfoDbItem) bool {
	if projectItem.Closed {
		return false
	}
	if projectItem.OwnerUserId == sessionItem.UserId || roleItem.BasicInfo.Admin || entryItem.CreateUserId == sessionItem.UserId {
		return true
	}
	return false
}
